package middleware

import (
	"blog_server/model"
	"blog_server/utils"
	"blog_server/utils/errmsg"
	"github.com/gin-gonic/gin"
	"strings"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenString := c.Request.Header.Get("Authorization")
		if tokenString == "" {
			code := errmsg.ERROR_NO_PRIVILEGE
			utils.Response(c, code, nil, errmsg.GetErrorMsg(code))
			c.Abort()
			return
		}

		if len(tokenString) < 7 || !strings.HasPrefix(tokenString, "Bearer ") {
			code := errmsg.ERROR_NO_PRIVILEGE
			utils.Response(c, code, nil, errmsg.GetErrorMsg(code))
			c.Abort()
			return
		}

		tokenString = tokenString[7:]
		token, claims, err := ParseToken(tokenString)

		if err != nil || !token.Valid {
			code := errmsg.ERROR_NO_PRIVILEGE
			utils.Response(c, code, nil, errmsg.GetErrorMsg(code))
			c.Abort()
			return
		}

		userId := claims.UserId
		db := model.GetDB()
		var user model.User
		db.Model(&model.User{}).Where("id = ?", userId).First(&user)
		c.Set("user", user)
		c.Next()
	}
}
